import { baseRoute } from '@/router';
import router, { resetRouter } from '@/router';

const state = {
  routes: [],
  accessedRoutes: []
};

const mutations = {
  SET_ROUTES(state, routes) {
    state.accessedRoutes = routes;
    state.routes = routes;
  },
  RESET_ROUTES(state) {
    state.routes = [];
    state.accessedRoutes = [];
  }
};

const actions = {
  getRoutes({ commit }, role) {
    return new Promise((resolve) => {
      // 过滤出需要在导航栏显示的路由
      let accessedRoutes = baseRoute.filter(route => !route.hidden);
      // 根据权限过滤路由
      accessedRoutes = filterAsyncRoute(accessedRoutes, role);
      commit('SET_ROUTES', accessedRoutes);
      resolve(accessedRoutes);
    });
  },

  //仅测试用，生产请去掉
  async changeRole({ commit, dispatch }, role) {
    await dispatch('user/login', role);
    resetRouter();
    await dispatch('getRoutes', role);
    await dispatch('tagsView/clearTag', null, { root: true });
  }
};

export function filterAsyncRoute(routes, role) {
  let arr = [];
  routes.forEach(item => {
    const temp = { ...item };
    if (hasChildren(temp, role)) {
      if (temp.children) {
        temp.children = filterAsyncRoute(temp.children, role);
      }
      arr.push(temp);
    }
  });
  return arr;
}

export function hasChildren(route, role) {
  if (route.hidden) {
    return false;
  }
  let roleIds = role.split(',');
  if (route.meta && route.meta.role) {
    return roleIds.includes(String(route.meta.role));
  }
  return true;
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
